package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 超时订单定时处理
     */
    @Scheduled(cron = "0 * * * * ?")
    public void timeOutOrder(){
        LocalDateTime now = LocalDateTime.now();
        log.info("定时处理超时未付款订单:{}",now);
        LocalDateTime localDateTime = now.plusMinutes(-15);
        // 把支付状态为0未付款,且下单时间超过15分钟的订单查询
        // 将查询的订单更新,订单状态为已经取消(6),订单取消时间为当前,订单取消原因为未支付订单超时
        List<Orders> ordersList = orderMapper.selectStatusAndTimeOut(Orders.PENDING_PAYMENT,localDateTime);

        ordersList.forEach(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(now);
            orders.setCancelReason("订单超时:未支付");

            orderMapper.update(orders);
        });
    }

    /**
     * 处理用户不点收货一直处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")
//    @Scheduled(cron = "0 * * * * ?")
    public void deliveryProgressOrder(){
        LocalDateTime now = LocalDateTime.now();
        log.info("定时处理派送中订单:{}",now);
        LocalDateTime localDateTime = now.plusMinutes(-60);
        List<Orders> ordersList = orderMapper.selectStatusAndTimeOut(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(now);
            orderMapper.update(orders);
        });

    }
}
